package com.ruitu.health_1.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.Gson;
import com.ruitu.arad.Arad;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.base.base_list.ListBaseAdapter;
import com.ruitu.arad.base.base_list.SuperViewHolder;
import com.ruitu.arad.util.CalcUtils;
import com.ruitu.arad.util.ToastUtils;
import com.ruitu.arad.view.EditTextCleanView;
import com.ruitu.health_1.R;
import com.ruitu.health_1.dao.bean.Confirm;
import com.ruitu.health_1.dao.bean.Pay;
import com.ruitu.health_1.mvp.model.OrderModel;
import com.ruitu.health_1.mvp.presenter.OrderPresenter;
import com.ruitu.health_1.util.CustomDialogUtil;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.Logg;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.cart.CouponList;
import com.ruitu.router_module.bean.cart.OmsCartItemListBean;
import com.ruitu.router_module.bean.order.ConfirmOrder;
import com.ruitu.router_module.bean.user.Address;
import com.ruitu.router_module.util.ReqUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CommitOrderActivity extends BaseActivity<OrderPresenter.GenerateP, OrderModel.GenerateM> {

    private DataAdapter adapter;

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_commit_order;
    }

    private ConfirmOrder order;

    private TextView tv_new_add_address;
    private LinearLayout ll_address;
    private Address address;
    private TextView tv_consignee;
    private TextView tv_address_type;
    private TextView tv_address;
    private TextView tv_tel;
    private TextView tv_total;

    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private LRecyclerView lRecyclerView;
    private String status;

    private String userId;
    private List<OmsCartItemListBean> omsCartItemListBeans;
    private ConfirmOrder.ISetting integrationConsumeSetting;

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("确认订单");
        userId = AppHolder.instance().getUser().getId();
        order = (ConfirmOrder) getIntent().getExtras().get("order");
        status = (String) getIntent().getExtras().get("status");
        //确认订单的set数据

        View view = View.inflate(this, R.layout.item_commit_order_header, null);
        tv_new_add_address = view.findViewById(R.id.tv_new_add_address);

        ll_address = view.findViewById(R.id.ll_address);
        tv_consignee = view.findViewById(R.id.tv_consignee);
        tv_address_type = view.findViewById(R.id.tv_address_type);
        tv_address = view.findViewById(R.id.tv_address);
        tv_tel = view.findViewById(R.id.tv_tel);
        tv_total = findViewById(R.id.tv_total);
        lRecyclerView = findViewById(R.id.l_recyclerview);
        lRecyclerView.setPullRefreshEnabled(false);
        if (order == null) {
            return;
        }
        omsCartItemListBeans = order.getCartPromotionItemList();
        if (order.getMemberReceiveAddress() == null) {
            tv_new_add_address.setVisibility(View.VISIBLE);
        } else {
            setAddress(order.getMemberReceiveAddress());
        }
        LinearLayoutManager manager = new LinearLayoutManager(this);
        lRecyclerView.setLayoutManager(manager);
        adapter = new DataAdapter(this);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(adapter);
        lRecyclerViewAdapter.addHeaderView(view);
        lRecyclerView.setAdapter(lRecyclerViewAdapter);
        adapter.setDataList(omsCartItemListBeans);
        setOnClickListener(ll_address);
        tv_total.setText(order.getCalcAmount().getTotalAmount());
        gold = Integer.parseInt(AppHolder.instance().getUser().getWallet().getBuyPoint());
        //金币规则
        integrationConsumeSetting = order.getIntegrationConsumeSetting();
    }

    public void setCommitSuc(Pay pay) {
        if (pay.getAddress() != null) {
            address = pay.address;
        }
        Bundle bundle = new Bundle();
        bundle.putSerializable("address", address);
        bundle.putSerializable("pay", pay);
        startActivity(PayOrderActivity.class, bundle);
        finish();
        Arad.bus.post(new EventModel(19122300));
    }

    private List<CouponList> couponList;
    private CouponList coupons;

    public void getUserCoupon(List<CouponList> coupons) {
        this.couponList = coupons;
        if (!isDataEmpty(coupons)) {
            showDialog();
        } else {
            ToastUtils.showShort("暂无可用优惠券");
        }
    }

    private void setAddress(Address memberReceiveAddressList) {
        address = memberReceiveAddressList;
        tv_consignee.setText(address.getName());
        tv_tel.setText(address.getPhoneNumber());
        tv_address.setText(address.getProvince() + address.getCity() + address.getRegion() + address.getDetailAddress());
        if (TextUtils.equals(memberReceiveAddressList.getDefaultStatus(), "1")) {
            tv_address_type.setVisibility(View.VISIBLE);
        } else {
            tv_address_type.setVisibility(View.GONE);
        }
        tv_new_add_address.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (ll_address == v) {
            Bundle bundle = new Bundle();
            bundle.putString("from", "from");
            startActivityForResult(AddressActivity.class, bundle, 979);
        }
    }

    private Confirm confirm;
    private List<Confirm> confirms;
    private Map<String, String> map;
    private OmsCartItemListBean cart;
    private int gold;
    private String itemGold;

    public void onConfirm(View view) {
        if (address == null) {
            ToastUtils.showShort("收货地址不能为空");
            return;
        }
        map = new HashMap<>();
        String id = null;
        List<OmsCartItemListBean> cartPromotionItemList = omsCartItemListBeans;
        if (TextUtils.equals(status, "1")) {
            OmsCartItemListBean cart = cartPromotionItemList.get(0);
            map.put("userId", userId);
            map.put("productId", cart.getProductId());
            map.put("skuId", cart.getProductSkuId());

            if (cart.getCoupon() != null) {
                id = cart.getCoupon().getId();
            }
            map.put("couponHistoryId", id);
            map.put("buyNum", cart.getQuantity() + "");
            map.put("addressId", address.getId());
            map.put("integral", cart.getUserIntegral());
            map.put("note", etc_content.getText().toString());
            showProgress();
            p.subOrder(ReqUtil.getBody(map, true));
            return;
        }
        confirms = new ArrayList<>();

        for (OmsCartItemListBean omsCartItemListBean : cartPromotionItemList) {
            confirm = new Confirm();
            confirm.setCartItemId(omsCartItemListBean.getId());
            confirm.setUseIntegration(omsCartItemListBean.getUserIntegral());
            if (omsCartItemListBean.getCoupon() != null) {
                id = omsCartItemListBean.getCoupon().getId();
            }
            confirm.setCouponHistoryId(id);
            confirms.add(confirm);
        }

        String json = new Gson().toJson(confirms);
        map.put("list", json);
        map.put("memberId", userId);
        map.put("memberReceiveAddressId", address.getId());
        map.put("note", etc_content.getText().toString());
        showProgress();
        p.generate(ReqUtil.getBody(map, true));
    }

    private boolean unUse = false;

    //取消优惠券解锁
    public void unLockSuc() {
        if (dialogUtil != null) {
            dialogUtil.dismiss();
        }
        omsCartItemListBeans.get(couponPosition).setCoupon(coupons);
        countOrderTotal();
    }

    EditText etc_content;

    public void setGoldUnLock(String data) {
        this.gold = Integer.parseInt(data);
        tv_gold_sum.setText("金币总数:" + data);
        omsCartItemListBeans.get(couponPosition).setUserIntegral(selectIntegral);
        countOrderTotal();
    }

    //设置选中的优惠券到指定的商品中
    public void setCoupon() {
        if (dialogUtil != null) {
            dialogUtil.dismiss();
        }
        omsCartItemListBeans.get(couponPosition).setCoupon(coupons);
        countOrderTotal();
    }

    //设置指定的积分到指定的商品上
    public void setGold(String gold) {
        this.gold = Integer.parseInt(gold);
        if (dialogUtil != null) {
            dialogUtil.dismiss();
        }
        omsCartItemListBeans.get(couponPosition).setUserIntegral(selectIntegral);
        countOrderTotal();
    }

    private void countOrderTotal() {
        adapter.notifyDataSetChanged();
        double couponTotal = 0;
        double goldTotal = 0;
        for (int i = 0; i < omsCartItemListBeans.size(); i++) {
            OmsCartItemListBean omsCartItemListBean = omsCartItemListBeans.get(i);
            if (omsCartItemListBean.getCoupon() != null) {
                couponTotal = CalcUtils.add(couponTotal, omsCartItemListBean.getCoupon().getPrice());
            }
            if (!TextUtils.isEmpty(omsCartItemListBean.getUserIntegral())) {
                goldTotal = CalcUtils.add(goldTotal, Integer.parseInt(omsCartItemListBean.getUserIntegral()) / integrationConsumeSetting.getUseUnit());
            }
        }
        tv_total.setText("" + CalcUtils.sub(order.getCalcAmount().getPayAmount(), CalcUtils.add(couponTotal, goldTotal)));
    }

    private String canUseIntegral;

    class DataAdapter extends ListBaseAdapter<OmsCartItemListBean> {

        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_confirm_order;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            ImageView iv_product_img = holder.getView(R.id.iv_product_img);
            TextView tv_product_name = holder.getView(R.id.tv_product_name);
            TextView tv_product_info = holder.getView(R.id.tv_product_info);
            TextView tv_price = holder.getView(R.id.tv_price);
            TextView tv_count = holder.getView(R.id.tv_count);
            TextView tv_coupon = holder.getView(R.id.tv_coupon);
            TextView tv_integral = holder.getView(R.id.tv_integral);
            LinearLayout ll_coupon = holder.getView(R.id.ll_coupon);
            LinearLayout ll_integral = holder.getView(R.id.ll_integral);
            RelativeLayout rl_coupon = holder.getView(R.id.rl_coupon);
            RelativeLayout rl_integral = holder.getView(R.id.rl_integral);
            LinearLayout ll_input = holder.getView(R.id.ll_input);
            etc_content = holder.getView(R.id.etc_content);
            if (position == mDataList.size() - 1) {
                ll_input.setVisibility(View.VISIBLE);
            } else {
                ll_input.setVisibility(View.GONE);
            }
            cart = mDataList.get(position);
            Glide.with(mContext).load(cart.getProductPic()).apply(Arad.opts).into(iv_product_img);
            tv_product_name.setText(cart.getProductSubTitle());
            tv_price.setText("" + cart.getPrice());
            tv_count.setText("X" + cart.getQuantity());
            if (TextUtils.equals(cart.getAllowUsedCouponStatus(), "0")) {
//                tv_coupon.setText("不可使用优惠券");
//                ll_coupon.setEnabled(false);
                rl_coupon.setVisibility(View.GONE);
            } else {
                rl_coupon.setVisibility(View.VISIBLE);
            }
            if (TextUtils.equals(cart.getAllowUsedGoldStatus(), "0")) {
//                tv_integral.setText("不可以使用金币");
                rl_integral.setVisibility(View.GONE);
            } else {
                rl_integral.setVisibility(View.VISIBLE);
                if (gold > integrationConsumeSetting.getUseUnit()) {
//                    rl_integral.setEnabled(false);
                    if (gold > Integer.parseInt(cart.getCanUseIntegral())) {
                        tv_integral.setText("最多可使用" + cart.getCanUseIntegral() + "积分");
                    } else {
                        tv_integral.setText("最多可使用" + Math.floor(gold / integrationConsumeSetting.getUseUnit()) * integrationConsumeSetting.getUseUnit() + "积分");
                    }
                } else {
//                    rl_integral.setEnabled(true);
                    tv_integral.setText("积分不足");
                }
            }
            StringBuffer buffer = new StringBuffer();
            if (!TextUtils.isEmpty(cart.getSp1())) {
                buffer.append(cart.getSp1());
            }
            if (!TextUtils.isEmpty(cart.getSp2())) {
                buffer.append("," + cart.getSp2());
            }
            if (!TextUtils.isEmpty(cart.getSp3())) {
                buffer.append("," + cart.getSp3());
            }
            tv_product_info.setText(buffer.toString());
            if (cart.getCoupon() != null) {
                tv_coupon.setText("当前优惠 " + cart.getCoupon().getPrice() + "元");
            } else {
                tv_coupon.setText("选取优惠券");
            }
            if (!TextUtils.isEmpty(cart.getUserIntegral())) {
                tv_integral.setText("当前使用积分:" + cart.getUserIntegral());
            } else {
                tv_integral.setText("最多可使用" + cart.getCanUseIntegral() + "积分");
            }
            ll_coupon.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (cart.getCoupon() != null) {
                        couponList = new ArrayList<>();
                        couponList.add(cart.getCoupon());
                        showDialog();
                        unUse = true;
                    } else {
                        showProgress();
                        p.getCanUseCoupon("" + cart.getPrice(), userId);
                    }
                    couponPosition = position;
                }
            });
            ll_integral.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    couponPosition = position;
                    cartItemId = cart.getId();
                    itemGold = cart.getUserIntegral();
                    canUseIntegral = cart.getCanUseIntegral();
                    showGoldDialog();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 979) {
            if (data != null) {
                address = (Address) data.getExtras().get("address");
                setAddress(address);
            }
        }
    }

    private CustomDialogUtil dialogUtil;

    private void showDialog() {
        View v = View.inflate(this, R.layout.dialog_coupon_list, null);
        ImageView iv_close = v.findViewById(R.id.iv_close);
        dialogUtil = new CustomDialogUtil(this, v, R.style.CommonBottomDialogStyle);
        RecyclerView recyclerView = v.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        CouponListAdapter adapter = new CouponListAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.setDataList(couponList);
        dialogUtil.setCanceledOnTouchOutside(true);
        dialogUtil.show();
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogUtil.dismiss();
            }
        });
    }

    private String selectIntegral;
    private String cartItemId;
    private TextView tv_gold_sum;

    private void showGoldDialog() {

        View v = View.inflate(this, R.layout.item_gold_input, null);
        tv_gold_sum = v.findViewById(R.id.tv_gold_sum);
        final TextView tv_confirm = v.findViewById(R.id.tv_confirm);
        final TextView tv_error = v.findViewById(R.id.tv_error);
        final EditTextCleanView etc_gold = v.findViewById(R.id.etc_gold);
        TextView tv_current_use = v.findViewById(R.id.tv_current_use);
        final CheckBox cb_current_use = v.findViewById(R.id.cb_current_use);
        LinearLayout ll_current_use = v.findViewById(R.id.ll_current_use);
        tv_gold_sum.setText("金币总数:" + gold);
        dialogUtil = new CustomDialogUtil(this, v, R.style.CommonBottomDialogStyle);
        dialogUtil.setCanceledOnTouchOutside(true);
        if (!TextUtils.isEmpty(itemGold)) {
            tv_current_use.setText(itemGold);
            ll_current_use.setVisibility(View.VISIBLE);
            cb_current_use.setChecked(true);
            etc_gold.setVisibility(View.GONE);
        }

        cb_current_use.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    selectIntegral = itemGold;
                    map = new HashMap<>();
                    map.put("cartItemId", cartItemId);
                    map.put("goldNum", itemGold);
                    map.put("memberId", userId);
                    memberGoldLock(map);
                    etc_gold.setVisibility(View.GONE);

                } else {
                    selectIntegral = null;
                    map = new HashMap<>();
                    map.put("cartItemId", cartItemId);
                    map.put("goldNum", itemGold);
                    map.put("memberId", userId);
                    p.memberGoldUnLock(ReqUtil.getBody(map, true));
                    etc_gold.setVisibility(View.VISIBLE);

                }
            }
        });
        etc_gold.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(s)) {
                    tv_error.setText("");
                    return;
                }
                int i = Integer.parseInt(s.toString());
                if (i % integrationConsumeSetting.getUseUnit() == 0 && i <= Integer.parseInt(canUseIntegral)) {
                    tv_confirm.setEnabled(true);
                    tv_error.setText("");
                } else {
                    if (i > gold) {
                        tv_confirm.setEnabled(false);
                        tv_error.setText("当前输入金币数量超出所拥有的金币数量");
                        return;
                    }
                    tv_error.setText("当前输入金币数量不符合规则");
                    tv_confirm.setEnabled(false);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cb_current_use.isChecked()) {
                    dialogUtil.dismiss();
                    return;
                }
                selectIntegral = etc_gold.getText().toString();

                map = new HashMap<>();
                map.put("cartItemId", cartItemId);
                map.put("goldNum", selectIntegral);
                map.put("memberId", userId);
                memberGoldLock(map);
            }
        });
        dialogUtil.show();
    }

    private void memberGoldLock(Map m) {
        showProgress();
        p.memberGoldLock(ReqUtil.getBody(m, true));
    }

    private int couponPosition;

    class CouponListAdapter extends ListBaseAdapter<CouponList> {
        public CouponListAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_coupon;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_amount = holder.getView(R.id.tv_amount);
            TextView tv_time = holder.getView(R.id.tv_time);
            TextView tv_use = holder.getView(R.id.tv_use);

            final CouponList coupon = mDataList.get(position);
            tv_name.setText(coupon.getName());
            tv_amount.setText("￥" + coupon.getPrice());
            tv_time.setText(coupon.getEndTime() + "前有效");
            if (unUse) {
                tv_use.setText("取消使用");
            } else {
                tv_use.setText("立即使用");
            }
            tv_use.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map map = new HashMap();
                    map.put("infoId", coupon.getId());
                    map.put("memberId", AppHolder.instance().getUser().getId());
                    if (unUse) {
                        coupons = null;
                        unLock();
                        unUse = false;
                    } else {
                        p.lock(ReqUtil.getBody(map, true));
                        coupons = coupon;
                    }
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        unLock();
        super.onBackPressed();
    }

    private void unLock() {
        Map map = new HashMap();
        map.put("memberId", AppHolder.instance().getUser().getId());
        p.unLock(ReqUtil.getBody(map, true));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        order.setCartPromotionItemList(omsCartItemListBeans);
        outState.putSerializable("data",  order);
        Logg.i("Save:  " + outState.get("data").toString());
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            Logg.i(savedInstanceState.get("data").toString());
        }
    }
}
